import pandas as pd
from dash import Dash, dcc, html
from dash.dependencies import Input, Output, State
from src.common.utils.wraper_fig import wraper_fig
from src.core.bias_analyzer.bias_analyzer import (
    stats_table_div,
    process_core_data, 
    get_attendance_stats,
    get_consumption_stats,
    plot_combined_analysis,
    plot_subject_distribution
)

def create_layout():
    return html.Div(
        children=[
            html.Header([
                html.H1('📉 学生偏科分析', 
                        style={'color': '#2c3e50', 'marginBottom': '20px', 'textAlign': 'center'}),
                html.Div([
                    dcc.Dropdown(
                        id='grade-dropdown',
                        options=[
                            {'label': '高一', 'value': '高一'},
                            {'label': '高二', 'value': '高二'},
                            {'label': '高三', 'value': '高三'},
                            {'label': '全部年级', 'value': None}
                        ],
                        placeholder="选择年级...",
                        clearable=False,
                        style={
                            'flex': 1,
                            'padding': '12px 8px',
                            'border': '2px solid #3498db',
                            'borderRadius': '8px',
                            'fontSize': '16px',
                            'backgroundColor': 'white'
                        }
                    ),
                    html.Button(
                        '开始分析 🔍',
                        id='analyze-button',
                        n_clicks=0,
                        style={
                            'marginLeft': '10px',
                            'padding': '12px 24px',
                            'backgroundColor': '#3498db',
                            'color': 'white',
                            'border': 'none',
                            'borderRadius': '8px',
                            'cursor': 'pointer',
                            'transition': 'all 0.3s',
                            ':hover': {
                                'backgroundColor': '#2980b9',
                                'transform': 'scale(1.05)'
                            }
                        }
                    )
                ],
                    style={
                        'display': 'flex',
                        'maxWidth': '800px',
                        'margin': '0 auto',
                        'padding': '20px'
                    }
                )
            ],
                style={
                    'backgroundColor': '#f8f9fa',
                    'padding': '2rem',
                    'boxShadow': '0 2px 4px rgba(0,0,0,0.1)'
                }
            ),

            html.Main([
                html.Section([
                    html.H2('📋 总体统计', style={'color': '#34495e', 'marginBottom': '15px'}),
                    dcc.Loading(
                        id='stats-loading',
                        type='circle',
                        children=html.Div(
                            id='stats-table',
                            style={
                                'padding': '20px',
                                'backgroundColor': 'white',
                                'borderRadius': '8px',
                                'boxShadow': '0 2px 4px rgba(0,0,0,0.05)'
                            }
                        )
                    )
                ],
                    style={
                        'maxWidth': '1200px',
                        'margin': '20px auto',
                        'padding': '0 20px'
                    }
                ),

                html.Section([
                    html.Div([
                        html.Div([
                            html.H2('📊 多维对比分析', style={'color': '#34495e', 'marginBottom': '15px'}),
                            dcc.Loading(
                                id='comparison-loading',
                                type='circle',
                                children=html.Div(
                                    html.Img(
                                        id='comparison-chart',
                                        style={
                                            'maxWidth': '100%',
                                            'height': '400px',
                                            'objectFit': 'contain',
                                            'display': 'block',
                                            'margin': '0 auto'
                                        }
                                    ),
                                    style={
                                        'backgroundColor': 'white',
                                        'padding': '20px',
                                        'borderRadius': '8px',
                                        'boxShadow': '0 2px 4px rgba(0,0,0,0.05)'
                                    }
                                )
                            )
                        ], style={'flex': 1}),
                        
                        html.Div([
                            html.H2('📖 科目分布分析', style={'color': '#34495e', 'marginBottom': '15px'}),
                            dcc.Loading(
                                id='subject-loading',
                                type='circle',
                                children=html.Div(
                                    html.Img(
                                        id='subject-distribution',
                                        style={
                                            'maxWidth': '100%',
                                            'height': '400px',
                                            'objectFit': 'contain',
                                            'display': 'block',
                                            'margin': '0 auto'
                                        }
                                    ),
                                    style={
                                        'backgroundColor': 'white',
                                        'padding': '20px',
                                        'borderRadius': '8px',
                                        'boxShadow': '0 2px 4px rgba(0,0,0,0.05)'
                                    }
                                )
                            )
                        ], style={'flex': 1})
                    ], 
                        style={
                            'display': 'flex',
                            'gap': '20px',
                            'flexWrap': 'wrap'
                        }
                    )
                ],
                    style={
                        'maxWidth': '1200px',
                        'margin': '20px auto',
                        'padding': '0 20px'
                    }
                )
            ],
                style={
                    'padding': '20px 0',
                    'backgroundColor': '#ecf0f1'
                }
            )
        ],
        style={
            'fontFamily': 'Segoe UI, system-ui',
            'minHeight': '100vh',
            'backgroundColor': '#ecf0f1'
        }
    )

def register_callbacks(app):
    @app.callback(
        [
            Output('stats-table', 'children'),
            Output('comparison-chart', 'src'),
            Output('subject-distribution', 'src')
        ],
        Input('analyze-button', 'n_clicks'),  
        [State('grade-dropdown', 'value')], 
        prevent_initial_call=True
    )
    def update_dashboard(n_clicks, selected_grade):
        merged_data, valid_scores, biased = process_core_data(selected_grade)
        attendance = get_attendance_stats()
        consumption = get_consumption_stats()
        merged_data = pd.merge(merged_data, attendance, 
                            left_on='bf_StudentID', right_on='bf_StudentID', 
                            how='left')
        merged_data = pd.merge(merged_data, consumption, 
                            on='bf_StudentID', how='left')
        
        stats_table = stats_table_div(merged_data)
        comparison_fig = plot_combined_analysis(merged_data)
        subject_fig = plot_subject_distribution(valid_scores, biased)

        return [
            stats_table,
            wraper_fig(comparison_fig),
            wraper_fig(subject_fig)
        ]

def init_bias_dash(server):
    app = Dash(
        __name__,
        server=server,
        url_base_pathname='/bias_analysis/'
    )
    app.layout = create_layout()
    register_callbacks(app)
    return app